package com.genius.util.Cache;

import com.genius.util.ConstPool.illuminatorPool;
import com.genius.util.Utils.BeanUtils.BeanLab;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.genius.util.ConstPool.RedisConstPool.CACHE_RANDOM_TTL;
import static com.genius.util.ConstPool.RedisConstPool.KEY_NAN;
import static com.genius.util.ConstPool.RedisConstPool.CACHE_RANDOM_TTL;
import static com.genius.util.ConstPool.RedisConstPool.KEY_NAN;

public class RedisUtil {
    public static void saveRedis(Map<String,Object> map, String key, long TTL, TimeUnit timeUnit, StringRedisTemplate stringRedisTemplate){
        stringRedisTemplate.opsForHash().putAll(key,map);
        stringRedisTemplate.expire(key,TTL,timeUnit);
    }

    private static void saveRedis(String json,String key,long TTL,TimeUnit timeUnit,StringRedisTemplate stringRedisTemplate){
        stringRedisTemplate.opsForValue().set(key,json);
        stringRedisTemplate.expire(key,TTL,timeUnit);
    }

    private static void saveRedis(String json,String key,long TTL,StringRedisTemplate stringRedisTemplate){
        TTL = TTL*illuminatorPool.second + getRandomTTL();
        saveRedis(json,key,TTL,TimeUnit.SECONDS,stringRedisTemplate);
    }

    public static void saveRedis(Object obj,String key,long TTL, StringRedisTemplate stringRedisTemplate){
        String json = Optional.ofNullable(obj).map(BeanLab::beanToJson).orElse(KEY_NAN);
        saveRedis(json,key,TTL,stringRedisTemplate);
    }

    public static <T> List<T> getList(String key, Class<T> tClass,StringRedisTemplate stringRedisTemplate) throws JsonProcessingException {
        String json = stringRedisTemplate.opsForValue().get(key);
        if(!Optional.ofNullable(json).filter(str->!str.equals(KEY_NAN)).isPresent()){
            return new ArrayList<>();
        }
        return BeanLab.jsonToArray(tClass,json);
    }

    public static void updateKeyTTL(String key,long TTL,StringRedisTemplate stringRedisTemplate){
        TTL = TTL*illuminatorPool.second + getRandomTTL();
        stringRedisTemplate.expire(key,TTL,TimeUnit.SECONDS);
    }

    public static long getRandomTTL(){
        return (new Random().nextInt((int)CACHE_RANDOM_TTL+1)+1)* illuminatorPool.second;
    }
}
